import time
import sys

def print_highlight(text, color="red"):
    """高亮打印（终端ANSI颜色）"""
    color_codes = {
        "red": "\033[91m",
        "yellow": "\033[93m",
        "green": "\033[92m",
        "blue": "\033[94m",
        "reset": "\033[0m"
    }
    return f"{color_codes[color]}{text}{color_codes['reset']}"

def validate_input(prompt, min_val=1):
    """输入校验：确保输入是有效整数"""
    while True:
        user_input = input(prompt).strip()
        if not user_input:  # 允许空输入（后续处理默认值）
            return None
        try:
            num = int(user_input)
            if num >= min_val:
                return num
            else:
                print(f"❌ 请输入大于等于{min_val}的整数！")
        except ValueError:
            print("❌ 输入无效！请输入一个整数。")

def clap_on_seven_ultimate():
    """终极版逢七拍手：顺序数数+拍手标注+分类统计"""
    # 欢迎界面
    print("\n" + "="*60)
    print(print_highlight("🎉 逢七拍手终极版 - 顺序数数+拍手标注 🎉", "blue"))
    print("="*60 + "\n")
    print("📌 规则：从1开始顺序数数，遇到以下情况拍手并标注：")
    print(f"   1. 7的倍数（{print_highlight('例：7、14、21', 'yellow')}）")
    print(f"   2. 包含数字7（{print_highlight('例：17、27、73', 'green')}）")
    print(f"   3. 既是倍数又包含7（{print_highlight('例：7、70、77', 'red')}）")
    print("="*60 + "\n")

    # 1. 自定义参数设置
    default_max = 100
    max_input = validate_input(f"请输入计数上限（默认{default_max}，直接回车使用默认值）：", min_val=7)
    max_num = max_input if max_input is not None else default_max

    # 选择模式：快速/逐字朗读
    mode = input("\n请选择输出模式（1=快速模式，2=逐字朗读模式，默认1）：").strip()
    mode = 1 if not mode or mode not in ["1", "2"] else int(mode)
    delay = 0.05 if mode == 1 else 0.3  # 快速模式延迟0.05秒，朗读模式0.3秒

    # 2. 初始化数据存储
    multiple_of_seven = []  # 7的倍数（非包含7）
    contains_seven = []     # 包含7（非倍数）
    both_conditions = []    # 既是倍数又包含7
    clap_records = []       # 存储所有拍手数字（带类型标记）

    # 3. 顺序数数+拍手判断（核心功能）
    print(f"\n🚀 开始从1数到{max_num}，遇到拍手数字会标注【👏】！")
    print("   按 Ctrl+C 可随时暂停，输入 'c' 继续，输入 'q' 退出当前轮次～")
    print("-"*60 + "\n")
    time.sleep(1)

    try:
        for num in range(1, max_num + 1):
            is_multiple = num % 7 == 0
            has_seven = '7' in str(num)
            clap = is_multiple or has_seven

            # 确定颜色和类型
            if is_multiple and has_seven:
                color = "red"
                type_tag = "双条件"
                both_conditions.append(num)
                clap_records.append((num, type_tag))
            elif is_multiple:
                color = "yellow"
                type_tag = "7的倍数"
                multiple_of_seven.append(num)
                clap_records.append((num, type_tag))
            elif has_seven:
                color = "green"
                type_tag = "包含7"
                contains_seven.append(num)
                clap_records.append((num, type_tag))
            else:
                color = "reset"
                type_tag = "普通数字"

            # 输出数字（拍手数字高亮+标注）
            if clap:
                print(f"{print_highlight(num, color)} 👏", end=' ', flush=True)
            else:
                print(num, end=' ', flush=True)

            # 每10个数字换行，便于查看
            if num % 10 == 0:
                print()

            # 延迟控制（模拟数数节奏）
            time.sleep(delay)

    except KeyboardInterrupt:
        # 暂停功能：捕获Ctrl+C，允许继续或退出
        print("\n\n⏸️  已暂停！")
        while True:
            choice = input("输入 'c' 继续数数，'q' 退出当前轮次：").strip().lower()
            if choice == 'c':
                print(f"\n▶️  从{num+1}继续数数...")
                print("-"*60 + "\n")
                # 继续循环（从num+1开始）
                for num_cont in range(num+1, max_num + 1):
                    is_multiple = num_cont % 7 == 0
                    has_seven = '7' in str(num_cont)
                    clap = is_multiple or has_seven

                    if is_multiple and has_seven:
                        color = "red"
                        type_tag = "双条件"
                        both_conditions.append(num_cont)
                        clap_records.append((num_cont, type_tag))
                    elif is_multiple:
                        color = "yellow"
                        type_tag = "7的倍数"
                        multiple_of_seven.append(num_cont)
                        clap_records.append((num_cont, type_tag))
                    elif has_seven:
                        color = "green"
                        type_tag = "包含7"
                        contains_seven.append(num_cont)
                        clap_records.append((num_cont, type_tag))
                    else:
                        color = "reset"
                        type_tag = "普通数字"

                    if clap:
                        print(f"{print_highlight(num_cont, color)} 👏", end=' ', flush=True)
                    else:
                        print(num_cont, end=' ', flush=True)

                    if num_cont % 10 == 0:
                        print()
                    time.sleep(delay)
                break
            elif choice == 'q':
                print("🔚 已退出当前轮次，显示已统计结果...")
                break
            else:
                print("❌ 输入无效！请输入 'c' 或 'q'")

    # 4. 结果汇总（分类统计+详细记录）
    total_clap = len(clap_records)
    print("\n\n" + "="*60)
    print(print_highlight(f"📊 1~{max_num} 逢七拍手游戏结果汇总", "blue"))
    print("="*60)
    print(f"📈 总计：{max_num}个数字，其中 {print_highlight(total_clap, 'red')} 个需要拍手！\n")

    # 分类统计（带颜色和数量）
    if both_conditions:
        print(f"🔴 双条件（既是倍数又包含7）：{print_highlight(' '.join(map(str, both_conditions)), 'red')}")
        print(f"   数量：{len(both_conditions)} 个")
    if multiple_of_seven:
        print(f"🟡 仅7的倍数：{print_highlight(' '.join(map(str, multiple_of_seven)), 'yellow')}")
        print(f"   数量：{len(multiple_of_seven)} 个")
    if contains_seven:
        print(f"🟢 仅包含7：{print_highlight(' '.join(map(str, contains_seven)), 'green')}")
        print(f"   数量：{len(contains_seven)} 个")

    # 拍手数字详细记录（按顺序+类型）
    print(f"\n📜 拍手数字详细记录（顺序+类型）：")
    for i, (num, tag) in enumerate(clap_records, 1):
        if tag == "双条件":
            print(f"   {i:2d}. {print_highlight(num, 'red')} - {tag}")
        elif tag == "7的倍数":
            print(f"   {i:2d}. {print_highlight(num, 'yellow')} - {tag}")
        else:
            print(f"   {i:2d}. {print_highlight(num, 'green')} - {tag}")

    print("\n" + "="*60)

def main():
    """主程序：支持重复游戏"""
    while True:
        clap_on_seven_ultimate()
        
        # 询问是否重新开始
        play_again = input("\n🔄 是否要再玩一轮？（y=是，n=否，默认n）：").strip().lower()
        if play_again != 'y':
            print(print_highlight("\n👋 感谢游玩！下次再见～", "blue"))
            break
        print("\n" + "="*60 + "\n")

if __name__ == "__main__":
    main()